const {
  querySysUserOptions
} = require('../../api/sysUser')
const {
  clearEmptyKey
} = require('../../utils/clearEmptyKey')
const {
  to,
  openLoading,
  closeLoading,
  showToast
} = getApp()
Page({
  data: {
    loadingType: '',
    dataList: [],
    chooseUserList: []
  },

  onLoad() {
    this.resetData()
    this.getSysUserList()
  },

  async getSysUserList() {
    const optionsData = {};
    const {
      companyId
    } = this.options
    if (companyId) {
      optionsData.companyId = companyId
    }

    clearEmptyKey(optionsData)
    openLoading()
    const [err, data] = await to(querySysUserOptions(optionsData))
    closeLoading()
    if (!err) {
      const choosedUserIds = this.options.choosedUserIds ? JSON.parse(this.options.choosedUserIds) : []
      data.forEach(item => {
        if (choosedUserIds.includes(item.userId)) {
          item.checked = true
        }
      })
      this.setData({
        dataList: data
      })

      if (data.length === 0) {
        this.setData({
          loadingType: 'empty'
        })
        return
      }

      this.setData({
        loadingType: 'end'
      })
    }
  },

  resetData() {
    this.setData({
      dataList: [],
      loadingType: ''
    })
  },

  handleSubmit() {
    if (!this.data.chooseUserList.length) {
      showToast('请选择至少一位使用人')
      return
    }
    const pages = getCurrentPages()
    const parentPage = pages[pages.length - 2];
    parentPage.setUserData(this.data.chooseUserList)

    wx.navigateBack()
  },

  checkboxChange(event) {
    const { value } = event.detail
    const result = this.data.dataList.filter(item => value.includes(item.userId + ''))

    this.setData({
      chooseUserList: result
    })
  }
})